package logic

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"strconv"
	"week_one/user_srv/models"
	"week_one/user_srv/pkg"
	user "week_one/user_srv/proto"
	"week_one/user_srv/service"
)

func (u *UserServer) Register(ctx context.Context, in *user.RegisterReq) (*user.RegisterRes, error) {
	//判断账号是否已经被注册
	_, err := service.GetUseByUsername(in.Username)
	if err == nil {
		return &user.RegisterRes{}, errors.New("账号已经被注册了")
	}
	//盐值加密
	salt := uuid.NewString()
	password := pkg.SaltMd5(salt, in.Password)
	//注册
	res, err := service.RegisterUser(&models.User{
		Username: in.Username,
		Password: password,
		Salt:     salt,
		Status:   1,
	})
	if err != nil {
		return &user.RegisterRes{}, err
	}
	return &user.RegisterRes{Userid: strconv.Itoa(int(res.ID))}, nil
}
func (u *UserServer) UserLogin(ctx context.Context, in *user.UserLoginReq) (*user.UserLoginRes, error) {
	//判断账号是否存在
	res, err := service.GetUseByUsername(in.Username)
	if err != nil {
		return &user.UserLoginRes{}, err
	}
	//盐值加密
	password := pkg.SaltMd5(res.Salt, in.Password)
	//验证密码
	if res.Password != password {
		return &user.UserLoginRes{}, errors.New("密码错误")
	}
	return &user.UserLoginRes{
		Id:       uint32(res.ID),
		Username: res.Username,
	}, nil
}
